<?php

class AdminCustomerController extends AdminController {

	public function getIndex()
	{
		$model  = new Customer;
		$customers = $model->customers();

		$this->layout->title   = trans('customer.customer_list');
		$this->layout->content = View::make('admin.customer.index', array('customers' => $customers));
	}

	public function getCreate()
	{
		$this->layout->title = trans('customer.create_customer');
		$this->layout->content = View::make('admin.customer.form');
	}

	public function postCreate()
	{
		$result = array('error' => true, 'message' => 'Only accept ajax request!');

		if(Request::ajax())
		{
			$data  = Input::all();
			
			$model = new Customer;
			
			$validator = $model->validator($data);

			if($validator->fails()){
				$result['error']   = true;
				$result['message'] = $model->getValidatorMessage();
			}else{
				$customer = $model->saveData($data);

				$result['error']   = false;
				$result['message'] = "Saved data";
				$result['data']    = $customer;
			}
		}

		return json_encode($result);
	}

	public function getEdit($id)
	{
		$customer = Customer::find($id);
		$data = array('customer' => $customer);

		$this->layout->title   = trans('customer.edit_customer');
		$this->layout->content = View::make('admin.customer.form', $data);
	}

	public function postDelete()
	{
		if(Request::ajax()){
			$id    = Input::get('id', 0);
			
			$model = new Customer;
			$customer = $model->findOrFail($id);

			$error   = true;
			$message = "customer not found!";

			if($customer !== false){
				$customer->delete();

				$error   = false;
				$message = "customer not found!";
			}

			return json_encode(array('error' => $error, 'message' => $message));
		}
	}
}